﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
using System.Text;

namespace Bioinformatics.Types
{
    public class GeneticSequenceCollection : Dictionary<string,GeneticSequence>
    {
        public Dictionary<char, float> StationaryProbabilities { get; private set; }
        public Alphabet Alphabet { get; private set; }
        public int SequenceLength { get; private set; }
        
        public static GeneticSequenceCollection ImportCollectionFromFile(string path)
        {
            var fstream = File.OpenRead(path);
            var binaryFormatter = new BinaryFormatter();
            var geneticSequenceArray = (GeneticSequence[])binaryFormatter.Deserialize(fstream);
            fstream.Close();

            var geneticSequenceCollection = new GeneticSequenceCollection();
            for (var i = 0; i < geneticSequenceArray.Length; i++)
                geneticSequenceCollection.Add(geneticSequenceArray[i].ToString(), geneticSequenceArray[i]);

            return geneticSequenceCollection;
        }

        public Dictionary<char, float> CalculateStationaryProbabilities()
        {
            StationaryProbabilities = new Dictionary<char, float>();
            var totalLength = 0;
            foreach (var sequence in Keys)
                for (var j = 0; j < this[sequence].Sequence.Length; j++)
                {
                    StationaryProbabilities[this[sequence].Sequence[j]]++;
                    totalLength++;
                }

            foreach (var character in StationaryProbabilities.Keys)
                StationaryProbabilities[character] /= totalLength;

            return StationaryProbabilities;
        }

        public void ExportCollectionToFile(string path)
        {
            //compile to list
            var geneticSequenceList = new List<GeneticSequence>();
            foreach (var geneticSequence in Values)
                geneticSequenceList.Add(geneticSequence);
            //serialize the list
            var fstream = File.OpenWrite(path);
            var binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(fstream, geneticSequenceList.ToArray());
            fstream.Close();
        }
    }
}
